package flexo.common;

/**
 * Simple reference counting class, to delete unused resources.
 * @author Miguel
 */
public abstract class ReferenceCount
{
	private int ref = 0;
	
	/**
	 * Call this method when you're going to use that resource for a while.
	 */
	public final void grab()
	{
		++ref;
	}
	
	/**
	 * Call this method when you don't need this resource anymore.
	 */
	public final void remove()
	{
		--ref;
		clean();
	}
	
	public final void clean()
	{
		if (ref == 0)
		{
			destroy();
		}
		else if (ref < 0)
		{
			flexo.Kernel.log("flexo.common.ReferenceCount", "Reference count lower than zero!", LogMsgType.ERROR);
			flexo.Kernel.error();
		}
	}

	/**
	 * Override this method if you need to do any resource cleanup.
	 * It'll be called at class destruction.
	 */
	protected abstract void destroy(); 
}
